<template>
  <div class="obligation-box" v-loading="loading">
    <div class="obligation-content">
      <div class="body-menu">
        <div class="top-title" @click="createSession">
          <img src="../../../../assets/images/create_session.png" />
          <p>新建会话</p>
        </div>
        <div class="menu_content">
          <h2>历史问答记录</h2>
          <p
            style="text-align: center; color: rgb(160 154 154)"
            v-if="session && session.length === 0"
          >
            暂无会话
          </p>
          <div
            class="menu-item"
            :class="selectId === item.id ? 'active' : ''"
            v-for="(item, index) in session"
            v-if="index < 10"
            :key="item.value"
            @click="selectedMenu(item)"
          >
            <i class="icon el-icon-s-comment"></i>
            <span class="name" :title="item.name">{{ item.name }}</span>
            <el-popover
              class="more"
              popper-class="el-popover-self"
              placement="right"
              trigger="hover"
            >
              <p @click="editSessionFn(item, index)">编辑</p>
              <p @click="delSessionFn(item, index)">删除</p>
              <i
                slot="reference"
                style="color: black"
                @click="editFn(item)"
                class="icon el-icon-more"
              ></i>
            </el-popover>
          </div>
        </div>
      </div>
      <div class="body-list">
          <!-- 问答方式 -->
          <div class="qaType" @click="qaTypeFn">
            {{ qaType }}
            <el-switch v-model="qaSwitch"> </el-switch>
          </div>

        <div class="message_content" ref="message_content">


          <div
            class="question"
            v-for="(item, index) in messageList"
            :key="index"
          >
            <img v-if="item.id === 1001" src="@/assets/images/profile.jpg" />
            <img
              v-if="item.id !== 1001"
              src="@/assets/images/login-background.jpg"
            />
            <div
              :class="item.id == 1001 ? 'answer_content' : ''"
              class="content"
            >
              <MarkdownPreview
                :initialValue="item.content"
                v-if="item.id !== 1001"
              ></MarkdownPreview>
              <!-- <div v-if="item.id !== 1001" v-html="renderedMarkdown"></div> -->
              <div v-else>{{ item.content }}</div>
              <div
                class="messageFile"
                v-if="item.source_list && item.source_list.length != 0"
              >
                <span>答案所引用的原文:</span>
                <div v-for="(H, I) in item.source_list" :key="I">
                  <p class="fileName" @click="fileInfoFn(H)">
                    文件名称:{{ H.file_detail.name + H.file_detail.ext }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="question_input">
          <el-input
            type="textarea"
            :resize="'none'"
            placeholder="请输入您的问题"
            clearable
            v-model="messageVal"
            @keydown.native="onKeyup"
          >
          </el-input>
          <!-- <el-button type="primary" plain @click="handleQA">发送</el-button> -->
          <img
            src="../../../../assets/images/sendMessage.png"
            @click="handleQA"
          />
        </div>
      </div>
    </div>
    <!-- <UploadDialog ref="uploadDialog"></UploadDialog> -->
    <!-- 新建会话 -->
    <el-dialog
      :title="title"
      :visible.sync="sessionVisible"
      :close-on-click-modal="false"
      width="30%"
      center
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="会话名称" prop="name">
          <el-input v-model="ruleForm.name" maxlength="50"></el-input>
        </el-form-item>
        <!-- <el-form-item>
    <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
    <el-button @click="resetForm('ruleForm')">重置</el-button>
  </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sessionClose">取 消</el-button>
        <el-button type="primary" @click="sessionCreate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 预览 -->
    <el-dialog
      class="preview"
      :visible.sync="previewVisible"
      :close-on-click-modal="false"
      width="100vw"
      center
    >
      <div class="main">
        <div class="file_box">
          <iframe
            id="iframe"
            ref="iframe"
            src=""
            frameborder="0"
            width="100%"
            height="100%"
          ></iframe>
        </div>
        <div class="tag_box">
          <h2>
            <span>知识导航条</span>
          </h2>
          <div
            v-for="tag in navigationList"
            :key="tag.node_id"
            class="navigation_item"
            :class="tag.node_id === activeTag.id ? 'tag_active' : ''"
            @click="handleNavigation(tag)"
          >
            {{ tag.text }}
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 预览视频 -->
    <el-dialog
      class="preview"
      :visible.sync="videoVideoVisible"
      :close-on-click-modal="false"
      width="100vw"
      center
    >
      <div class="main">
        <div class="file_box">
          <div class="video_model">
            <div id="video"></div>
          </div>
        </div>
        <div class="tag_box">
          <h2>
            <span>知识导航条</span>
          </h2>
          <div
            v-for="tag in navigationList"
            :key="tag.node_id"
            class="navigation_item"
            :class="tag.node_id === activeTag.id ? 'tag_active' : ''"
            @click="handleNavigation(tag)"
          >
            {{ tag.text }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { MarkdownPreview } from "vue-meditor";

// import MarkdownIt from 'markdown-it';
// import mk from '@iktakahiro/markdown-it-katex';

import { mapState } from "vuex";
export default {
  name: "index",
  components: { MarkdownPreview },
  data() {
    return {
      previewVisible: false,
      videoVideoVisible: false,
      loading: false,
      sessionVisible: false,
      qaType: "知识库问答",
      qaSwitch: true,
      fileText: "",
      fileInfoVisible: false,
      title: "新建会话",
      ruleForm: {
        name: "",
      },
      rules: {
        name: [{ required: true, message: "请输入会话名称", trigger: "blur" }],
      },
      analysisData: {},
      messageVal: "",
      session: [],
      selectId: "",
      messageList: [],
      filesArr: [],
      checkedList: [], // 选中的数据
      example: null,
      source_list: [],
      navigationList: [],
      downloadUrl: "",
      activeTag: {},
      player: null,
      dataInfo: null,
      isEND:false,
      str_list:''
    };
  },
  computed: {
    renderedMarkdown() {
      const md = new MarkdownIt();
      md.use(mk);
      return md.render(this.markdownContent);
    }
  },
  activated() {
    this.getFilesList();
  },
  created() {},
  mounted() {
    // this.qaFn();
    console.log(this.session);
    // //在页面刷新时将vuex里的信息保存到localStorage里
    // window.addEventListener("beforeunload", this.localPreserve());

    this.getSession();
  },
  watch: {
    // session: {
    //   handler(newVal, oldVal) {
    //     this.localPreserve();
    //   },
    //   deep: true,
    // },
  },
  methods: {
    // 获取会话列表
    getSession() {
      this.$http({
        url: "/knowledgeQa/get",
        method: "GET",
      }).then(({ data }) => {
        console.log(data, "fffff");
        this.session = data.data.session;
        if (this.session && this.session.length > 0) {
          this.selectedMenu(this.session[0])
        }
      });
    },
    sessionStart(item) {
      this.$http({
        url: "/knowledgeQa/add",
        method: "post",
        data: item,
      }).then(({ data }) => {
        console.log(data, "fffff");
      });
    },
    sessionDel(id) {
      this.$http({
        url: "/knowledgeQa/delete",
        method: "post",
        data: {
          id,
        },
      }).then(({ data }) => {});
    },
    upload() {
      this.$refs.uploadDialog.init();
    },
    qaTypeFn() {
      this.qaType = this.qaType == "知识库问答" ? "生成式问答" : "知识库问答";
      this.qaSwitch = this.qaType == "知识库问答" ? true : false;
    },
    editFn(item) {
      console.log("fff", item);
    },
    // 编辑会话
    editSessionFn(item) {
      this.title = "编辑会话";
      this.sessionVisible = true;

      this.ruleForm.name = item.name;
      this.ruleForm.id = item.id;
      console.log(item, "ffffsss");
    },
    delSessionFn(item, index) {
      this.$confirm("此操作将删除该会话, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.session.splice(index, 1);
          this.sessionDel(item.id);
          if (item.id === this.selectId) {
            this.messageList = [];
            this.selectId = "";
          }
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {});
    },
    handleNavigation(navigation) {
      // let text = []
      // if(navigation.trace_location.table_index){
      //  text = navigation.trace_location.table_index == -1 ? navigation.text : navigation.trace_location.pdf_search_str;

      // }else{
      //   text = navigation.text
      // }
      // console.log(this.dataInfo, "fff");
      // this.$set(this.activeTag, "id", navigation.node_id);
      // // this.$set(this.activeTag, "labelName", navigation.text);
      // this.$set(this.activeTag, "labelName", text);
      // // 需要判断当前是文件还是视频
      // if (
      //   [".avi", ".mp4", ".wmv", "mov"].includes(this.dataInfo.file_detail.ext)
      // ) {
      //   console.log("navigation--->", navigation);
      //   // 操作视频播放器跳到对应位置 文件解析进入到对应位置
      //   this.player.seek(navigation.seg_time[0]);
      // } else {
      //   setTimeout(() => {
      //     var iframe = document.querySelector("#iframe");
      //     this.populateIframe(
      //       iframe,
      //       [["token", +localStorage.getItem("token")]],
      //       this.downloadUrl
      //     );
      //   }, 0);
      // }

      let text = []
      if(navigation.trace_location.table_index){
       text = navigation.trace_location.table_index == -1 ? navigation.text : navigation.trace_location.pdf_search_str;

      }else{
        text = navigation.text
      }
      console.log('知识导航条切换',  navigation)
      this.$set(this.activeTag, "id", navigation.node_id);
      // this.$set(this.activeTag, "labelName", navigation.text);
      this.$set(this.activeTag, "labelName", text);
      // 需要判断当前是文件还是视频
      if (this.dataInfo.fileType == "video") {
        console.log("navigation--->", navigation);
        // 操作视频播放器跳到对应位置 文件解析进入到对应位置
        this.player.seek(navigation.seg_time[0]);
      } else {
        setTimeout(() => {
          let iframe = document.getElementById("iframe");
          let iframeWindow = iframe.contentWindow;
          let iframeDocument = iframe.contentDocument || iframeWindow.document;
          let hidden = iframeDocument.getElementById("findbar");
          hidden.classList.remove("hidden");
          let findInput = iframeDocument.getElementById("findInput");
          // findInput.value = navigation.text;
          findInput.value = text;
          findInput.focus();
          iframeDocument.getElementById("findHighlightAll").click();
          iframeDocument.getElementById("findHighlightAll").click();
        }, 0);
      }
    },
    // 文件详情
    fileInfoFn(item) {
      let that = this;
      console.log(item);
      const row = item.file_detail;
      this.$set(this.activeTag, "id", "");
      this.$set(this.activeTag, "labelName", "");

      // 过滤以"paragraph"结尾的数据

      this.navigationList = item.items.filter((word) =>
        word.chunk_type.includes("paragraph")
      );

      console.log("查看过滤后的内容", this.navigationList);
      this.dataInfo = item;
      this.$http({
        url: "/file/getUrl",
        method: "get",
        params: {
          id: row.id,
        },
      }).then(({ data }) => {
        if ([".avi", ".mp4", ".wmv", "mov"].includes(item.file_detail.ext)) {
          that.videoVideoVisible = true;
          that
            .$http({
              url: "/knowledgeData/video/verification",
              method: "get",
              params: {
                id: row.id,
              },
            })
            .then(({ data }) => {
              that.analysisData = JSON.parse(data.data.videoJson);
              console.log(that.analysisData, "4444");
            });
          console.log("获取文件之后地址", this.$config.VUE_APP_BASE_API+data.data.downloadUrl);
          setTimeout(() => {
            that.player = new that.$Player({
              id: "video", // 元素id
              lang: "zh", // 设置中文
              volume: 0, // 默认静音
              autoplay: false, // 自动播放
              screenShot: false, // 开启截图功能
              height: 200,
              // 视频地址
              url: this.$config.VUE_APP_BASE_API+data.data.downloadUrl,
              // 封面图
              // poster:'',
              fluid: true, // 填满屏幕 （流式布局）
              playbackRate: [0.5, 0.75, 1, 1.5, 2], // 传入倍速可选数组
            });
            // 监听播放进度事件
            that.player.on("timeupdate", that.onTimeUpdate);
            that.handleNavigation(this.navigationList[0])
          }, 300);
          return;
        } else {
          this.previewVisible = true;
          this.downloadUrl = this.$config.VUE_APP_BASE_API+data.data.downloadUrl;
          console.log("获取文件之后地址", this.$config.VUE_APP_BASE_API+data.data.downloadUrl);
          this.previewVisible = true;
          setTimeout(() => {
            var iframe = document.querySelector("#iframe");
            this.populateIframe(
              iframe,
              [["token", +localStorage.getItem("token")]],
              this.$config.VUE_APP_BASE_API+data.data.downloadUrl
            );
            this.handleNavigation(this.navigationList[0])
          }, 0);
        }
      });
    },
    populateIframe(iframe, headers, url) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.responseType = "blob";
      headers.forEach((header) => {
        xhr.setRequestHeader(header[0], header[1]);
      });

      xhr.onreadystatechange = () => {
        if (xhr.readyState === xhr.DONE) {
          if (xhr.status === 200) {
            console.log(URL.createObjectURL(xhr.response), "ffff");
            this.previewUrl = URL.createObjectURL(xhr.response);
            console.log("预览地址", URL.createObjectURL(xhr.response));
            // iframe.src =
            //   "./static/pdfjs/web/viewer.html?file=" +
            //   URL.createObjectURL(xhr.response);
            iframe.src =
              "./static/pdfjs/web/viewer.html?keyword=" +
              this.activeTag.labelName +
              "&file=" +
              URL.createObjectURL(xhr.response);
          }
        }
      };
      xhr.send();
    },
    onTimeUpdate(currentTime) {
      //   console.log("Current time:", currentTime.currentTime);
      this.navigationList.map((item) => {
        if (
          currentTime.currentTime > item.seg_time[0] &&
          currentTime.currentTime < item.seg_time[1]
        ) {
          this.$set(this.activeTag, "id", item.node_id);
          this.$set(this.activeTag, "labelName", item.text);
        }
      });
    },
    handleClose() {
      this.fileInfoVisible = false;
      this.fileText = "";
    },
    // 问询
    qaFn(val) {
      let that = this;
      const result = that.session.find((S) => S.id == that.selectId);

      // 新增：流式读取状态跟踪
      const streamState = {
        buffer: '',
        partialMessage: false
      };
      console.log("问答参数", result);
      let url = `${this.$config.VUE_APP_BASE_API}/kms-core-svc/qa`;
      // if (process.env.NODE_ENV == "production") {
      //   const hostUrl = location.protocol + "//" + location.host;
      //   url = `${hostUrl}/kms-core-svc/api/v1/chat/aqa`;
      // } else {
      //   url = `${process.env.VUE_APP_BASE_API_QA}/v1/chat/aqa`;
      // }

      fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          'token':localStorage.getItem('token')
        },
        body: JSON.stringify({
          user_input: val,
          chat_type: this.qaType == "知识库问答" ? "rag" : "raw",
          session_id: result.id,
          history: result.message,
        }),
      })
        .then(async (response) => {
          if (!response.body) throw new Error('No response body');
        
          const reader = response.body.getReader();
          const decoder = new TextDecoder('utf-8');
          
          // 使用递归处理流式数据
          const processChunk = async () => {
            const { done, value } = await reader.read();
            if (done) {
              // 处理最后可能残留的数据
              if (streamState.buffer.length > 0) {
                that.parseDataString(streamState.buffer);
              }
              // 保存会话
              console.log("问答结束1111");
              that.sessionStart(result);
              return;
            }

            // 分块解码（处理可能的中文字符截断）
            const chunk = decoder.decode(value, { stream: true });
            streamState.buffer += chunk;

            // 特殊处理：检查缓冲区末尾是否是截断的JSON
            const processBuffer = () => {
              let startPos = 0;
              while (true) {
                const dataPos = streamState.buffer.indexOf('data: ', startPos);
                if (dataPos === -1) break;

                const endPos = streamState.buffer.indexOf('\n', dataPos);
                if (endPos === -1) {
                  // 不完整消息，保留在缓冲区
                  streamState.buffer = streamState.buffer.slice(dataPos);
                  return;
                }

                // 提取完整消息
                const message = streamState.buffer.slice(dataPos + 6, endPos);
                try {
                  const parsed = JSON.parse(message);
                  // 直接更新消息列表（避免parseDataString的二次处理）
                  const lastMsg = that.messageList[that.messageList.length - 1];
                  if (parsed.content) lastMsg.content = (lastMsg.content || '') + parsed.content;
                  if (parsed.source_list) lastMsg.source_list = parsed.source_list;
                } catch (e) {
                  console.warn('JSON解析失败，尝试修复:', e);
                  // 尝试修复后重新处理
                  streamState.buffer = streamState.buffer.slice(dataPos);
                  return;
                }

                startPos = endPos + 1;
              }
              // 清理已处理的数据
              streamState.buffer = startPos < streamState.buffer.length 
                ? streamState.buffer.slice(startPos) 
                : '';
            };

            processBuffer();
            that.scrollBottom();
            return processChunk(); // 递归处理下一块
          };

          await processChunk();
          that.$nextTick(() => {
            that.scrollBottom();
          });
          // // 检查响应是否为流式响应
          // if (response.body && typeof response.body.getReader === "function") {
          //   // 获取响应数据流
          //   const reader = response.body.getReader();
          //   // 定义处理数据流的函数
          //   const processStream = async () => {
          //     let { done, value } = await reader.read();
          //     while (!done) {
          //       // 处理接收到的数据块
          //       const data = new TextDecoder().decode(value);
          //       console.log("看看初始数据===>", data);
          //       // 需要判断 数据中存有data: 并且后面有两个空格存在才会走这个处理方法
          //       if (data.includes("data: ")) {
          //         this.parseDataString(data);
          //       }else{
          //         if(that.isEND){
          //           that.str_list += data
          //                   console.log("看看整理后的",this.str_list)
          //         // try {
          //         // console.log("延迟看看附件", JSON.parse(that.str_list));
          //         // this.messageList[this.messageList.length - 1].source_list = JSON.parse(that.str_list).source_list;
          //         // } catch {
          //         // // return;
          //         // }
          //         }
          //       }
          //       // 读取下一个数据块
          //       ({ done, value } = await reader.read());

          //       that.scrollBottom();
          //     }
          //     console.log("问答结束1111");
          //     that.sessionStart(result);
          //   };
          //   // 启动处理数据流
          //   processStream();
          //   that.$forceUpdate();
          //   that.scrollBottom();
          // } else {
          //   // 处理非流式响应
          //   console.log("Response is not a stream:", response);
          // }
        })
        .catch((error) => {
          console.error("Error:", error);
        });
    },
    parseDataString(dataString) {
      let that = this;
      const result = that.session.find((S) => S.id == that.selectId);

      dataString
        .split("data: ")
        .filter((item) => item !== "")
        .map((item) => {
          // const str = item.replace(/\n\n/, "");
          let str = item
          try {
            if (item.includes('content')) {
              str = JSON.parse(item).content
            }
          } catch (error) {
            console.log('JSON解析错误：', error);
          }
          console.log("ffff=====>", str);
          if (item.includes("context_text")) {
            console.log("这个是附件实例",item)
            that.str_list += item
            that.isEND = true;
            try {
              // console.log("延迟看看附件", JSON.parse(str));
              this.messageList[this.messageList.length - 1].source_list = JSON.parse(item).source_list;
              // result.message[result.message.length - 1].source_list =
              //   JSON.parse(item).source_list;
            } catch {
              return;
            }
            // return;
          } else {
            if (str.includes("---end---")) {
              return;
            }
            // const message = this.messageList[this.messageList.length - 1].content + str;
            // this.messageList[this.messageList.length - 1].content = message;
            const message =
              result.message[result.message.length - 1].content + str;
            result.message[result.message.length - 1].content = message;
          }
        });

      console.log("结尾打印====>", dataString);

      //   if (data.includes("context_text")) {
      //     const source = data.split("data: ").slice(2);
      //     if(source && source.length > 0) {
      //       result.message[result.message.length - 1].source_list =
      //       JSON.parse(source).source_list;
      //     }

      //   }
      //   let val = data.split("data: ")[1].replace(/\n\n/, "");

      //   if (val.includes("---end---")) {
      //     val = val.replace("---end---", "");
      //   }
      //   const message =
      //     result.message[result.message.length - 1].content + val;
      //   result.message[result.message.length - 1].content = message;
      //   // 读取下一个数据块
      //   ({ done, value } = await reader.read());
    },
    // 开始问答
    handleQA() {
      if (!this.messageVal) {
        this.$message.error("输入内容不能为空");
        return;
      }
      console.log("this.session, this.selectId", this.session, this.selectId);
      if (!this.selectId) {
        const session = {
          id: window.$guid(),
          name: this.messageVal,
          message: [],
        };
        this.sessionStart(session);
        this.session.unshift(session);
        this.selectId = this.session[0].id;
        this.selectedMenu(this.session[0]);
      }
      const result = this.session.find((S) => S.id == this.selectId);
      // return
      console.log(result, "result");
      result.message.push({
        id: 1001,
        name: "自己",
        content: this.messageVal,
      });
      result.message.push({
        id: 1002,
        name: "AI机器人",
        content: "",
        source_list: [],
      });
      this.qaFn(this.messageVal);
      setTimeout(() => {
        this.messageVal = "";
        this.scrollBottom();
      }, 100);
    },
    scrollBottom() {
      this.$refs.message_content.scrollTop =
        this.$refs.message_content.scrollHeight;
    },
    // 新建会话
    createSession() {
      // this.sessionVisible = true;
      // this.title = "新建会话";
      this.selectId = "";
      this.messageList = [];
    },
    sessionCreate() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.title == "新建会话") {
            this.session.unshift({
              id: window.$guid(),
              name: this.ruleForm.name,
              message: [],
            });

            if (this.session.length > 10) {
              this.session.pop();
            }
          } else {
            const result = this.session.find((h) => h.id == this.ruleForm.id);
            result.name = this.ruleForm.name;

            this.sessionStart(this.ruleForm);
          }
          this.sessionVisible = false;
          this.ruleForm.name = "";
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    sessionClose() {
      this.$refs.ruleForm.resetFields();
      this.sessionVisible = false;
    },
    // 按回车发送信息
    onKeyup(e) {
      // console.log("onKeyup",e)
      if (e.keyCode === 13) {
        e.preventDefault();
        this.handleQA();
      }
    },
    // 获取附件列表
    getFilesList() {
      // this.loading = true
      // this.$http({
      //   url: '/userGrid/tools/list',
      //   methods: 'GET',
      //   params: {
      //     pageSize: -1,
      //     fileName: this.searchForm.name,
      //     manualType: this.menuActive
      //   }
      // })
      //   .then(({ data }) => {
      //     if (data && data.success) {
      //       this.filesArr = data.page.list
      //       this.loading = false
      //     }
      //   })
      //   .catch(() => {
      //     this.loading = false
      //   })
    },
    // 菜单选择
    selectedMenu(item) {
      this.selectId = item.id;
      this.messageList = this.session.find(
        (S) => S.id == this.selectId
      ).message;
      console.log(this.messageList);
      this.getFilesList();
      setTimeout(() => {
        this.scrollBottom();
      }, 100);
    },
    // 附件选中
    checked(data) {
      this.checkedList = data;
    },
    // 删除数据
    delFiles() {
      this.$confirm("是否确定删除所选择附件？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          const ids = this.checkedList.join(",");
          this.$http({
            url: "/userGrid/tools/delete",
            method: "DELETE",
            params: {
              ids: ids,
            },
          })
            .then(({ data }) => {
              if (data && data.success) {
                this.$message.success("删除成功！");
                this.checkedList = [];
                this.loading = false;
                this.getFilesList();
              }
            })
            .catch(() => {
              this.$message.success("删除失败！");
              this.loading = false;
            });
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped lang="scss">
/* 在这里添加KaTeX的CSS样式 */
// @import 'katex/dist/katex.min.css';
.obligation-box {
  height: calc(100vh - 101px);
  width: 100%;
  ::v-deep .markdown-preview {
    border-radius: 5px;
    p {
      margin-bottom: 0;
    }
  }

  .obligation-content {
    overflow-y: hidden;
    // background: #fff;
    height: 100%;
    // border: 1px solid #ddd;
    // box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    display: flex;
    padding: 20px;

    .body-menu {
      flex: 0 0 240px;
      background: white;
      .top-title {
        flex: 0 0 240px;
        font-size: 22px;
        font-weight: bold;
        border-bottom: 1px solid #ddd;
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 10px;
        border-radius: 5px;
        cursor: pointer;
        img {
          width: 24px;
          height: 24px;
        }
      }

      .menu_content {
        padding: 0 20px;
        // height: 100%;
        overflow-y: auto;
        max-height: calc(100% - 66px);
        // position: relative;

        h2 {
          font-size: 18px;
          color: #1c2126;
          font-weight: bold;
          position: sticky;
          top: 0;
          z-index: 99;
          background: #fff;
          padding: 15px 10px;
          margin: 0;
        }

        .menu-item {
          padding: 10px;
          cursor: pointer;
          margin-bottom: 10px;
          display: flex;
          // justify-content: center;
          align-items: center;
          gap: 10px;

          .name {
            width: 160px;
            white-space: nowrap; /* 确保文本在一行内显示 */
            overflow: hidden; /* 隐藏溢出的内容 */
            text-overflow: ellipsis; /* 使用省略号表示文本溢出 */
          }
          i {
            color: #7682f6;
          }

          &.active {
            background: #e8f5ff;
            font-weight: 550;
          }

          &:hover {
            background: #e8f5ff;
          }
        }
      }
    }

    .body-list {
      flex: 1;
      padding: 0px 20px;
      position: relative;

      img {
        object-fit: contain;
      }

      .message_content {
        height: calc(100vh - 290px);
        overflow-y: auto;
        position: relative;
        margin-top: 70px;
      }

      .question {
        display: flex;
        align-items: flex-start;
        padding: 10px 20px;

        img {
          width: 30px;
          height: 30px;
          margin-right: 10px;
        }

        .answer_content {
          background: #0084ff !important;
          color: white;
          border-radius: 5px;
          height: auto;
          //margin-bottom: 10px;
          //padding: 20px;
          font-size: 16px;
        }

        .content {
          padding: 20px;
          border: 1px solid #e7dede;
          border-radius: 10px;
          background: white;
        }
      }

      .answer {
        display: flex;
        align-items: flex-start;

        .answer_box {
          width: 100%;

          .answer_content {
            // background: #fff;
            background: #f0f5fe;
            border-radius: 5px;

            height: calc(100vh - 360px);
            margin-bottom: 10px;
            padding: 5px 10px;
          }

          .answer_resource {
            // background: #fff;
            background: #f0f5fe;
            border-radius: 5px;
            padding: 5px 10px;

            .answer_resource_list {
              background: #fff;
              margin: 10px;
              padding: 2px 10px;
              border-radius: 10px;
            }
          }
        }
      }

      .question_input {
        // margin: 20px 0;
        position: relative;

        img {
          position: absolute;
          top: 30%;
          right: 20px;
          cursor: pointer;
        }
        ::v-deep .el-textarea__inner {
          height: 80px !important;
          border: none;
        }

        ::v-deep .el-button {
          position: absolute;
          right: 20px;
          bottom: 10px;
        }
      }
    }
  }
}

/*隐藏浏览器滚轮*/
::-webkit-scrollbar {
  // display: none;
}

/*滚动条整体样式*/
/*高宽分别对应横竖滚动条的尺寸*/
::-webkit-scrollbar {
  width: 6px;
  height: 1px;
}

/*滚动条里面小方块*/
::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 3px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);
  background: #999;
}

/*滚动条里面轨道*/
::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px #fff;
  border-radius: 3px;
  background: #ededed;
}

/*隐藏浏览器滚轮*/
::-moz-scrollbar {
  // display: none;
}

/*滚动条整体样式*/
/*高宽分别对应横竖滚动条的尺寸*/
::-moz-scrollbar {
  width: 6px;
  height: 1px;
}

/*滚动条里面小方块*/
::-moz-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 3px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.05);
  background: #999;
}

/*滚动条里面轨道*/
::-moz-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px #fff;
  border-radius: 3px;
  background: #ededed;
}

.qaType {
  float: right;
    position: absolute;
    top: 0px;
    width: 97%;
    height: 60px;
    background: white;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 10px;
    padding-right: 20px;
}
.messageFile {
  border-top: 1px solid #4c5a67;
  margin-top: 20px;
  padding-top: 20px;

  .fileName {
    color: #0084ff;
    cursor: pointer;
  }
}
.preview ::v-deep.el-dialog {
  margin-top: 0px !important;
  height: 100%;
}

.preview ::v-deep.el-dialog__body {
  width: 100vw !important;
  height: 96% !important;
  position: absolute;
  padding: 0px !important;
}

.main {
  display: flex;
  height: 100%;
  .file_box {
    flex: 1;
    // width: 50%;
    border-right: 1px solid #d8d8d8;
  }
  .video_text_box {
    width: 30%;
    border-right: 1px solid #d8d8d8;
    overflow: auto;
    .box-card {
      margin-bottom: 10px;
    }
  }
  .tag_box {
    width: 25%;
    padding-left: 10px;
    height: 100%;
    overflow: auto;
    .navigation_item {
      margin: 10px;
      padding: 10px;
      background: #f1f2f5;
      cursor: pointer;
      // border:1px solid red;
    }
    .tag_active {
      background: #67deb2;
      color: #fff;
    }
  }
  .video_model {
    width: 100%;
    height: 100%;
    #video {
      width: 100%;
      height: 100% !important;
    }
  }

  .more {
    float: right;
  }
}
</style>
<style lang="scss">
.el-popover-self {
  width: 70px !important;
  min-width: 70px !important;
  padding: 0px !important;
  margin: 0px !important;
  p {
    // width: 70px !important;
    padding-top: 6px !important;
    margin: 0px !important;
    text-align: center;
    cursor: pointer;
    height: 30px;
  }
}
</style>
